#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>
#include <QNetworkInterface>
#include "mycombobox.h"
#include "MessageType.h"
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    server = new QTcpServer(this);


    //创建数据库对象
   // database =new MyDatabase;
    connect(ui->comboBoxChildren,&MyComboBox::on_ComboBox_cliecked,this,&Widget::mComboBox_refresh);
    connect(server,SIGNAL(newConnection()),this,SLOT(on_newClient_connect()));
    ui->btnlineout->setEnabled(false);
    ui->btnstoplisten->setEnabled(false);

    //将客户端的ip地址记录到combox中
    QList<QHostAddress>address = QNetworkInterface::allAddresses();
    for(QHostAddress tmp:address)
    {
        if(tmp.protocol()==QAbstractSocket::IPv4Protocol)
        {
            ui->comboBoxaddr->addItem(tmp.toString());
        }
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_newClient_connect()
{
    //当有连接的时候进行
    if(server->hasPendingConnections())
    {
        //创建套接字
        QTcpSocket *connection = server->nextPendingConnection();
        qDebug()<<"client Addr:"<<connection->peerAddress().toString()<<"client port"<<connection->peerPort();
        ui->textEditRev->append("客户端地址"+ connection->peerAddress().toString()+ "\n客户端端口:" +QString::number(connection->peerPort()));
        connect(connection,SIGNAL(readyRead()),this,SLOT(on_readRead_handler()));
        connect(connection,SIGNAL(disconnected()),this,SLOT(mdisconnected()));
    }
}

void Widget::on_readRead_handler()
{
    //读取客户端的数据
    QList<QMap<QString,QString>>Database;
    QByteArray senData;
    QTcpSocket *senderSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray revData = senderSocket->readAll();
    QMap<QString,QString>data;
    //对从传来的数据类型进行转换
    data=MyDatabase::byteArrayToMapCustom(revData);
    //判断消息类型
    //检查连接类型并记录套接字
    if( data.value("senderType") == DOCTORMESSAGE)
    {
        doctorsocket = senderSocket;
        qDebug()<<"doctorsocket:"<<doctorsocket;
        qDebug()<<"Doctor client identified and socket stored.";
    }
    if( data.value("senderType") == PATIENTMESSAGE)
    {
        patientsocket = senderSocket;
        qDebug()<<"patientsocket:"<<patientsocket;
        qDebug()<<"Patient  client identified and socket stored.";
    }
    if(data.value("type")==PATIENTUSRDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataPatient(data);
            break;
        case DELETE:
            MyDatabase::deleteDataPatient(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataPatient(data);
            break;
        case SELECT:
            Database=MyDatabase::checkDataPatient(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==DOCTORUSRDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
             MyDatabase::insertDataDoctor(data);
            break;
        case DELETE:
            MyDatabase::deleteDataDoctor(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataDoctor(data);
            break;
        case SELECT:
            Database=MyDatabase::checkDataDoctor(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==DEPARTMENTDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataDepartment(data);
            break;
        case DELETE:
            MyDatabase::deleteDataDepartment(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataDepartment(data);
            break;
            //进行处理
        case SELECT:
            Database=MyDatabase::checkDataDepartment(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==COMMUNICATE)
    {
        //根据目标转发消息
        if(data.value("target")==DOCTORMESSAGE)
        {

           doctorsocket->write(revData);
            qDebug()<<"data："<<revData;
        }else if(data.value("target")==PATIENTMESSAGE)
        {
            patientsocket->write(revData);
            qDebug()<<"data："<<revData;
        }
        else
        {
            qWarning()<<"Target not found or not connected.";
        }
    }else if(data.value("type") == MEDICIALRECDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataMedicialrec(data);
            break;
        case DELETE:
            MyDatabase::deleteDataMedicialrec(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataMedicialrec(data);
            break;
            //进行处理
        case SELECT:
            Database=MyDatabase::checkDataMedicialrec(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")== PRESCRIPTIONDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataPrescription(data);
            break;
        case DELETE:
            MyDatabase::deleteDataPrescription(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataPrescription(data);
            break;
            //进行处理
        case SELECT:
            Database=MyDatabase::checkDataPrescription(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==HEALTHASSESSMENTDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataHealthassessment(data);
            break;
        case DELETE:
            MyDatabase::deleteDataHealthassessment(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataHealthassessment(data);
            break;
            //进行处理
        case SELECT:
            Database=MyDatabase::checkDataHealthassessment(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==REGISTRATIONDATABASE)
    {
        switch(data.value("databaseoperator").toInt())
        {
        case INSERT:
            MyDatabase::insertDataRegistration(data);
            break;
        case DELETE:
            MyDatabase::deleteDataRegistration(data);
            break;
        case UPDATE:
            MyDatabase::modifiDataRegistration(data);
            break;
            //进行处理
        case SELECT:
            Database=MyDatabase::checkDataRegistration(data);
            senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
            senderSocket->write(senData);
            break;
        }
    }else if(data.value("type")==DOCTORINFO)
    {
        Database=MyDatabase::checkDataDoctorinfo(data);
        senData=MyDatabase::convertQMapArrayToByteArrayCustom(Database);
        senderSocket->write(senData);
        qDebug()<<senData;
    }else
    {
        qDebug()<<"无效的信息";
    }
    ui->textEditRev->append("客户端："+revData);
}

void Widget::mdisconnected()
{
    //对服务断开连接进行处理
    QTcpSocket *tmpSock = qobject_cast<QTcpSocket*>(sender());
    qDebug()<<"client out!";
    ui->textEditRev->append("客户端断开!");
    tmpSock->deleteLater();

}

void Widget::mComboBox_refresh()
{
    //将客户端的端口刷新
    QList<QTcpSocket*>tcpSocketClients =server->findChildren<QTcpSocket*>();
    ui->comboBoxChildren->clear();
    for(QTcpSocket*tmp:tcpSocketClients)
    {
        ui->comboBoxChildren->addItem(QString::number(tmp->peerPort()));
    }
    ui->comboBoxChildren->addItem("all");
}

void Widget::on_btnlisten_clicked()
{
    //开始监听
    int port= ui->lineEditport->text().toInt();
    if(!server->listen(QHostAddress(ui->comboBoxaddr->currentText()),port))
    {
        qDebug()<<"listenError";
        QMessageBox msgBox;
        msgBox.setWindowTitle("监听失败");
        msgBox.setText("端口号被占用");
        msgBox.exec();
    }
    ui->btnlisten->setEnabled(false);
    ui->btnlineout->setEnabled(true);
    ui->btnstoplisten->setEnabled(true);
}



//服务端给指定的客户端发送信息
void Widget::on_btnsend_clicked()
{
    //发送信息给客户端
    QList<QTcpSocket*>tcpSocketClients =server->findChildren<QTcpSocket*>();
    if(ui->comboBoxChildren->currentText()!="all")
    {
        tcpSocketClients[childIndex]->write(ui->textEditsend->toPlainText().toStdString().c_str());
    }
    else
    {
        for(QTcpSocket*tmp:tcpSocketClients)
        {
            tmp->write(ui->textEditsend->toPlainText().toStdString().c_str());
        }
    }
}


void Widget::on_comboBoxChildren_activated(int index)
{
    childIndex = index;
}


void Widget::on_btnstoplisten_clicked()
{
    //停止监听处理
    QList<QTcpSocket*>tcpSocketClients =server->findChildren<QTcpSocket*>();
    for(QTcpSocket*tmp:tcpSocketClients)
    {
        tmp->close();
    }
    server->close();
    ui->btnlisten->setEnabled(true);
    ui->btnstoplisten->setEnabled(false);
    ui->btnlineout->setEnabled(false);
}


void Widget::on_btnlineout_clicked()
{
    //断开处理
    on_btnstoplisten_clicked();
    delete server;
    this->close();
}

